package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.User;
import com.itheima.health.security.JokerPasswordEncoder;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author likepei
 * @Date 2020/2/5 14:31
 * @Version v1.0
 * @Description 用户操作的控制器
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    //依赖注入, 通过Dubbo的远程调用, 把Zookeeper中的UserService实现类对象进行 赋值userService
    @Reference
    private UserService userService;

    @Autowired
    private JedisPool jedisPool;

    /**
     * 根据用户ID返回关联的角色ID
     *
     * @param id
     * @return
     */
    @RequestMapping("findRoleIdsByUserId")
    public Result findRoleIdsByUserId(Integer id) {
        try {
            List<Integer> roleIds = userService.findRoleIdsByUserId(id);
            return new Result(true, "根据ID查询用户角色成功", roleIds);
        } catch (Exception e) {
            return new Result(false, "根据ID查询用户角色失败");
        }
    }


    @RequestMapping("findById")
    public Result findById(Integer id) {
        try {
            User user = userService.findById(id);
            user.setPassword(null);
            return new Result(true, "根据ID查询用户成功", user);
        } catch (Exception e) {
            return new Result(false, "根据ID查询用户失败");
        }
    }


    /**
     * 分页查询用户
     *
     * @return
     */
    //@PreAuthorize("hasAuthority('USER_QUERY')")
    @RequestMapping("/findPage")
    public Result findPage(@RequestBody QueryPageBean queryPageBean) {

        try {
            PageResult pageResult = userService.findPage(queryPageBean);
            return new Result(true, "分页查询用户成功", pageResult);
        } catch (Exception e) {
            return new Result(false, "分页查询用户失败");
        }

    }

    /**
     * 给用户密码加密
     *
     * @return
     */
    public User encodePassword(User user) {
        String password = user.getPassword();
        if (password != null && password.length() > 0) {
            String encode = new JokerPasswordEncoder().encode(password);
            user.setPassword(encode);
        }
        return user;

    }

    /**
     * 编辑用户
     *
     * @return
     */
    @PreAuthorize("hasAuthority('USER_EDIT')")
    @RequestMapping("/editUser")
    public Result editUser(@RequestBody User user, Integer[] userRoleIds) {
        try {
            User user1 = this.encodePassword(user);
            userService.editUser(user1, userRoleIds);
            return new Result(true, "编辑用户成功");
        } catch (Exception e) {
            return new Result(false, "编辑用户失败");
        }
    }

    /**
     * 删除用户
     *
     * @return
     */
    @PreAuthorize("hasAuthority('USER_DELETE')")
    @RequestMapping("/deleteUser")
    public Result deleteUser(Integer id) {
        try {
            userService.deleteUserById(id);
            return new Result(true, "删除用户成功");
        } catch (Exception e) {
            return new Result(false, "删除用户失败");
        }
    }

    /**
     * 添加用户
     *
     * @return
     */
    @PreAuthorize("hasAuthority('USER_ADD')")
    @RequestMapping("/addUser")
    public Result addUser(Integer[] userRoleIds, @RequestBody User user) {
        //添加用户
        try {
            User user1 = this.encodePassword(user);
            userService.addUser(user1, userRoleIds);
            return new Result(true, "添加用户成功");
        } catch (Exception e) {
            return new Result(false, "添加用户失败");
        }
    }


    /**
     * 获取用户名
     *
     * @return
     */
    @RequestMapping("/getUsername")
    public Result getUsername() {
        try {
            //从授权框架上下文对象中 获取认证对象
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            //再从 认证对象中 获取授权框架用户对象User
            User user = (User) authentication.getPrincipal();
            //用户对象User 获取 用户名
            String username = user.getUsername();
            //获取成功, 返回成功信息, 并返回用户名
            return new Result(true, MessageConst.ACTION_SUCCESS, username);
        } catch (Exception e) {
            e.printStackTrace();
            //获取失败,返回失败信息
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }

    /**
     * 无权访问处理器
     *
     * @return
     */
    @RequestMapping("/accessDenied")
    public Result accessDenied() {
        return new Result(false, "权限不足请更换账号");
    }


    /**
     * 登录成功
     *
     * @return
     */
    @RequestMapping("/loginSuccess")
    public Result loginSuccess(HttpServletRequest request) {

        //region 跨域存放对象
        //Jedis jedis = jedisPool.getResource();
        //HttpSession session = request.getSession();
        //String sessionId = session.getId();
        ////安全容器里拿到验证对象
        //Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //User user = (User) authentication.getPrincipal();
        //jedis.set(sessionId, JSON.toJSONString(user));
        //jedis.expire(sessionId, 5 * 60);
        //jedis.close();
        //endregion

        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }

    /**
     * 登录失败
     *
     * @return
     */
    @RequestMapping("/loginFail")
    public Result loginFail() {
        return new Result(false, "登录失败");
    }

    @RequestMapping("/needLogin")
    public Result needLogin() {
        return new Result(false, "需要登录");
    }


    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public Result login(String username, String password) {
        //打印日志, 获取浏览器发来的数据
        log.debug("UserController login......u={}...p={}", username, password);

        //调用service层的方法, 完成用户登录操作
        if (userService.login(username, password)) {
            log.debug("login success");
            return new Result(true, MessageConst.ACTION_SUCCESS);
        } else {
            log.debug("login fail");
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }
}
